package com.zk.babala.util;

import com.zk.babala.vo.GiteeFileInfo;

import java.util.HashMap;
import java.util.Map;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONUtil;

/**
 * @Author: zhangke
 * @Date: 2023/4/21 17:02
 */
public class GiteeUtil {
    public static String HISTORY_FILE_URL = "https://gitee.com/api/v5/repos/babal/document/contents/history.json";
    public static String APP_FILE_URL = "https://gitee.com/babal/babala/releases/download/1.0.0/babala.apk";

    public static GiteeFileInfo getFileInfo(String fileUrl) {
        String response = RequestUtil.getStr(fileUrl + "?access_token=7835cfc970ff44f510f9d4ef56e997c9");
        GiteeFileInfo fileInfo = JSONUtil.toBean(response, GiteeFileInfo.class);
        return fileInfo;
    }

    public static String getRemoteHistoryJson() {
        GiteeFileInfo historyVO = GiteeUtil.getFileInfo(GiteeUtil.HISTORY_FILE_URL);
        if (historyVO.getContent() != null) {
            return Base64.decodeStr(historyVO.getContent());
        }
        return "";
    }

    public static String uploadFile(String content) {
        Map<String, String> data = new HashMap<>();
        data.put("access_token", "7835cfc970ff44f510f9d4ef56e997c9");
        data.put("message", "update");
        data.put("branch", "master");
        data.put("content", Base64.encode(content));
        data.put("sha", GiteeUtil.getFileInfo(GiteeUtil.HISTORY_FILE_URL).getSha());
        return RequestUtil.putData(GiteeUtil.HISTORY_FILE_URL, JSONUtil.toJsonStr(data));
    }

}
